package com.yuzhe.controller;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.yuzhe.model.HomeType;
import com.yuzhe.utils.JSONResult;
import org.apache.commons.lang3.StringUtils;
import org.n3r.idworker.Sid;

import java.util.List;

public class HomeTypeController extends Controller {

    public void saveHomeType() {
        String id = Sid.next();
        String typeName = getPara("typeName");
        String sort = getPara("sort");
        if (StringUtils.isBlank(typeName)) {
            renderJson(JSONResult.errorMsg("分类名称不能为空"));
            return;
        }

        if (StringUtils.isBlank(sort)) {
            renderJson(JSONResult.errorMsg("分类排序不能为空"));
            return;
        }

        boolean result = HomeType.dao.set("id", id).set("typename", typeName)
                .set("sort", sort).save();
        if (result) {
            renderJson(JSONResult.ok());
        } else {
            renderJson(JSONResult.errorMsg("添加失败"));
        }
    }

    public void updateHomeType() {
        String id = getPara("id");
        if (StringUtils.isBlank(id)) {
            renderJson(JSONResult.errorMsg("分类id不能为空"));
            return;
        }

        String typeName = getPara("typeName");
        String sort = getPara("sort");
        if (StringUtils.isBlank(typeName)) {
            renderJson(JSONResult.errorMsg("分类名称不能为空"));
            return;
        }

        if (StringUtils.isBlank(sort)) {
            renderJson(JSONResult.errorMsg("分类排序不能为空"));
            return;
        }

        boolean result = HomeType.dao.set("id", id).set("typename", typeName)
                .set("sort", sort).update();
        if (result) {
            renderJson(JSONResult.ok());
        } else {
            renderJson(JSONResult.errorMsg("更新失败"));
        }
    }

    //获取所有分类列表
    public void getHomeTypeList() {
        String sql = "select * from home_type order by sort desc";
        List<HomeType> homeTypes = HomeType.dao.find(sql);
        renderJson(JSONResult.ok(homeTypes));
    }

    //删除分类
    public void deleteHomeType() {
        String ids = getPara("ids");
        if (StringUtils.isBlank(ids)) {
            renderJson(JSONResult.errorMsg("分类id不能为空"));
            return;
        }

//        String[] idsArray = ids.split(",");
        String sql = "delete from home_type where id in (" + ids + ")";
        int update = Db.update(sql);
        if (update > 0) {
            renderJson(JSONResult.ok());
        } else {
            renderJson(JSONResult.errorMsg("批量删除失败"));
        }
    }


}
